const ws = require('nodejs-websocket')
const PORT = 12300
// eslint-disable-next-line no-unused-vars
let serverConnection = null
let clientConnection = null

const server = ws.createServer(connect => {
  console.log('New Connection')
  connect.on('text', data => {
    console.log('Received Data: ' + data)
    let dataJson = JSON.parse(data)
    switch (dataJson.type) {
      case 'handshake':
        // 握手
        if (dataJson.data.model === 'server') {
          serverConnection = connect
        } else {
          clientConnection = connect
        }
        break
      case 'responseSize':
        if (serverConnection != null) {
          serverConnection.sendText(data)
        }
        // eslint-disable-next-line no-fallthrough
      default:
        if (clientConnection != null) {
          clientConnection.sendText(data)
        }
        // 配置更新
        break
    }

    // 连接断开 触发close事件
    connect.on('close', (code, reason) => {
      console.log('connection closed')
      code && console.log(code)
      reason && console.log(reason)
    })

    // error：监听服务异常事件，放置因报错而断掉整个服务。
    connect.on('error', () => {
      // 如果触发了close事件，就会走error异常事件(刷新也会)，所以必须加error
      console.log('连接出现异常')
    })
  })
})

server.listen(PORT, () => {
  console.log('WebSocket服务端启动成功')
})
// Socket End
